#include "StatusGrpcClient.h"
#include "const.hpp"
#include "message.grpc.pb.h"
#include <cstddef>
#include <grpcpp/client_context.h>
#include <grpcpp/support/status.h>
StatusGrpcClient::StatusGrpcClient() {
  std::string host = config.get<std::string>("StatusServer.Host");
  std::string port = config.get<std::string>("StatusServer.Port");
  size_t poolSize = config.get<size_t>("StatusServer.PoolSize");
  _pool.reset(new RpcConnectPool<StatusService>(poolSize, host, port));
}

GetChatServerRsp StatusGrpcClient::GetChatServer(int uid) {
  ClientContext context;
  GetChatServerRsp reply;
  GetChatServerReq request;
  request.set_uid(uid);
  auto stub = _pool->GetConnection();
  if (stub == nullptr) {
    reply.set_error(ErrorCodes::RPCFailed);
    return reply;
  }
  Status status = stub->GetChatServer(&context, request, &reply);
  if (status.ok()) {
    _pool->returnConnection(std::move(stub));
    return reply;
  } else {
    _pool->returnConnection(std::move(stub));
    reply.set_error(ErrorCodes::RPCFailed);
    return reply;
  }
}

StatusGrpcClient::~StatusGrpcClient() { _pool->Close(); }